//
//  OAuthViewController.swift
//  sinaWeibo
//
//  Created by liii on 16/7/5.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        self.view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 自定义导航栏的view默认是透明的
        self.view.backgroundColor = UIColor.grayColor()
        
        // 添加导航栏"关闭"按钮
        setNavigationBar()
        
        // 加载授权请求页面
        loadOAuthAuthorizeRequest()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 界面消失的时候,关闭HUD
        SVProgressHUD.dismiss()
    }
    
    private func loadOAuthAuthorizeRequest() {
        let urlString = "https://api.weibo.com/oauth2/authorize" + "?client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeOAuthPage")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoSetAccount")
    }
    
    @objc private func closeOAuthPage() {
        // 关闭modal
        dismissViewControllerAnimated(true, completion: {() -> Void in
            
            // 发起通知, 切换控制器
            defaultCenter.postNotificationName(switchRootVcNotification, object: nil)
            print("111%@", NSThread.currentThread())
        })
    }
    
    @objc private func autoSetAccount() {
        // "自动填充"脚本
        let js = "document.getElementById('userId').value='408930755@qq.com',document.getElementById('passwd').value='liii2016'"
        // 执行脚本
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}

// 扩展代理方法
extension OAuthViewController: UIWebViewDelegate {

    // 开始加载请求, 显示HUD
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    // 请求加载完毕, 关闭HUD
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 可以监测到webView每次加载新的页面发起的网络请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL!)
        // 过滤url为nil的情况
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        // 过滤掉回调页
        if urlString .containsString("code") {
            
            // 过滤为url为nil的情况
            guard let query = request.URL?.query else {
                return false
            }
            // 将String转换成NSString,再截取code
            let codeString = "code="
            let code = (query as NSString).substringFromIndex(codeString.characters.count)
            // 拿code换取access_token
            UserAccount.sharedAccount.loadAccessTokenRequest(code, completed: { (isSuccess) -> () in
                // 登陆失败, 给出提示
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus(appErrorTip)
                }
                
                // 登陆成功, 关掉授权页
                self.closeOAuthPage()
            })
            return false
        }
        
        // 其他情况正常执行
        return true
    }
}
